package com.chx.utils;

/**
 * @author 夏天
 * @date 2018/4/28 下午10:17
 * @Description:
 */
public class ByteUtil {

    public static byte[] short2bytes(short v) {
        byte[] targets = new byte[2];
        for (int i = 0; i < 2; i++) {
            int offset = (targets.length - 1 - i) * 8;
            targets[i] = (byte) ((v >>> offset) & 0xff);
        }
        return targets;

        /*byte[] b = new byte[2];

        b[1] = (byte) v;
        b[0] = (byte) (v >>> 8);

        return b;*/

        /*int temp = v;
        byte[] b = new byte[2];
        for (int i = 0; i < b.length; i++) {
            // 将最低位保存在最低位
            b[i] = new Integer(temp & 0xff).byteValue();
            // 向右移8位
            temp = temp >> 8;
        }
        return b;*/
    }

    public static short bytes2short(byte[] b) {
        short s = 0;
        // 最低位
        short s0 = (short) (b[0] & 0xff);
        short s1 = (short) (b[1] & 0xff);
        s1 <<= 8;
        s = (short) (s0 | s1);
        return s;
    }

    public static byte[] long2bytes(long v) {
        byte[] targets = new byte[8];
        for (int i = 0; i < 8; i++) {
            int offset = (targets.length - 1 - i) * 8;
            targets[i] = (byte) ((v >>> offset) & 0xff);
        }
        return targets;
        /*long temp = v;
        byte[] b = new byte[8];
        for (int i = 0; i < b.length; i++) {
            // 将最低位保存在最低位
            b[i] = new Long(temp & 0xff).byteValue();
            // 向右移8位
            temp = temp >>> 8;
        }
        return b;*/
    }

    public static byte[] int2bytes(int v) {
        byte[] targets = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (targets.length - 1 - i) * 8;
            targets[i] = (byte) ((v >>> offset) & 0xff);
        }
        return targets;
        /*byte[] b = new byte[4];

        b[3] = (byte) v;
        b[2] = (byte) (v >>> 8);
        b[1] = (byte) (v >>> 16);
        b[0] = (byte) (v >>> 24);

        return b;*/


        /*int temp = v;
        byte[] b = new byte[4];
        for (int i = 0; i < b.length; i++) {
            // 将最低位保存在最低位
            b[i] = new Integer(temp & 0xff).byteValue();
            // 向右移8位
            temp = temp >> 8;
        }
        return b;*/
    }
}
